package com.xuwei.base.reflect;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

/**
 * 高级反射
 * @author 许伟
 * @since 2015年10月31日
 */
public class Demo4 {

	 public static Object exeMethod(Object obj, String methodName, Object[] vals, Class<?> ...args){
	    	try {
	    		Method method = obj.getClass().getDeclaredMethod(methodName, args);
	    		method.setAccessible(true);
	    		return method.invoke(obj, vals);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	
	    	return args;
	 }
	 
	 public void sysDate(Date date){
		 System.out.println(date.toLocaleString());
	 }
	 public String formatDate(Date date, String fmtStyle){
		 return new SimpleDateFormat(fmtStyle).format(date);
	 }
	 
	 public void printSomething(String arg0, Date date, char ch, boolean b){
		 System.out.println("String:"+arg0+" Date:"+date+" char:"+ch+" boolean"+b);
	 }
	 
	 
	 @Test
	 public void test1() {
//		System.out.println(new Demo4().formatDate(new Date(), "yyyy-MM-dd"));
//		 Object res =  exeMethod(new Demo4(), "formatDate",new Object[]{new Date(),"yyyy-MM-dd"}, Date.class , String.class);
//		 System.out.println(res);
		 
		 exeMethod(new Demo4(),
				 "printSomething", 
				 new Object[]{"Hello",new Date(), 'A', true},
				 String.class, Date.class, char.class, boolean.class);
	 }
	 
	 @Test
	 public void test2(){
		 try {
	    		Class clazz = Demo4.class;
	    		Demo4 ref = (Demo4) clazz.newInstance();
	    		Method m = clazz.getDeclaredMethod("formatDate", Date.class,String.class);//得到方法干嘛？
	    		m.setAccessible(true);
	    		System.out.println(m.invoke(ref,new Date(),"yyyy-MM-dd"));
				
			} catch (Exception e) {
				e.printStackTrace();
			}
	 }
	 
	
}
